<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/9/11 0011
 * Time: 上午 10:53
 */
namespace app\api\controller;

use app\common\Helper;
use app\common\model\Specialofferrule;
use app\common\model\Storecancelrecord;
use app\common\model\Userreceivetic;
use app\common\validate\WriteOffTicket;
use think\Db;
use think\Exception;
use think\Request;

class Ticket extends Base{


    /**
     * 创建优惠券
     * @return \think\response\Json
     */
    public function createTicket(Request $request){
        $param = $request->param();
        Db::startTrans();
        try{
            if(!$this->checkparam($param)){
                return show(config('status.ERROR_STATUS'),'参数不合法','参数不合法');
            }
            $SpecialofferruleModel = new Specialofferrule();
            $SpecialofferruleId = Helper::getUUID();
            $SpecialofferruleModel->id = $SpecialofferruleId;
            $specialofferrule = $param['ticket']['specialofferrule'];
            $this->getspecialofferrule($specialofferrule,$SpecialofferruleModel);
            $SpecialofferruleModel->save();
            $TicketModel = new \app\admin\model\Ticket();
            $ticketId = Helper::getUUID();
            $TicketModel->id = $ticketId;
            $TicketModel->name = $specialofferrule['specialOfferName'];
            $TicketModel->specialOfferId = $SpecialofferruleId;
            $TicketModel->storeId = $param['storeId'];
            $TicketModel->beginTime = $param['ticket']['beginTime'];
            $TicketModel->endTime = $param['ticket']['endTime'];
            if($TicketModel->endTime <= date('Y-m-d',time())){
                $TicketModel->status = 2;
            }else{
                $TicketModel->status = 5;
            }
            $TicketModel->getGross = $param['ticket']['getGross'];
            $TicketModel->limitGross = 1;
            $TicketModel->getMethod = $param['ticket']['getMethod'];
            $TicketModel->buyTicketMoney = isset($param['ticket']['buyTicketMoney'])?$param['ticket']['buyTicketMoney']:NULL;
            $TicketModel->specialOfferStatement = $param['ticket']['specialOfferStatement'];
            $TicketModel->backgroundImg = $param['ticket']['backgroundImg'];
            $TicketModel->remainGross = $param['ticket']['getGross'];
            $TicketModel->firstCommission = isset($param['ticket']['firstCommission'])?$param['ticket']['firstCommission']:0;
            $TicketModel->secCommission = isset($param['ticket']['secCommission'])?$param['ticket']['secCommission']:0;
            $TicketModel->save();
            Db::commit();
            return show(config('status.SUCCESS_STATUS'),'创建优惠券成功','创建优惠券成功');
        }catch (Exception $ex){
            Db::rollback();
            return show(config('status.ERROR_STATUS'),'创建优惠券失败','创建优惠券失败');

        }

    }

    private function getspecialofferrule($specialofferrule,$SpecialofferruleModel){
        if(isset($specialofferrule['deductionMoney']) && !empty($specialofferrule['deductionMoney'])){
            $SpecialofferruleModel->deductionMoney = $specialofferrule['deductionMoney'];
        }elseif (isset($specialofferrule['commodityForFree']) && !empty($specialofferrule['commodityForFree'])){
            $SpecialofferruleModel->commodityForFree = $specialofferrule['commodityForFree'];
        }elseif (isset($specialofferrule['chargeMoney']) && !empty($specialofferrule['chargeMoney'])){
            $SpecialofferruleModel->chargeMoney = $specialofferrule['chargeMoney'];
            $SpecialofferruleModel->commodityForCharge = $specialofferrule['commodityForCharge'];
        }elseif (isset($specialofferrule['consumeMoney']) && !empty($specialofferrule['consumeMoney'])){
            $SpecialofferruleModel->consumeMoney = $specialofferrule['consumeMoney'];
            $SpecialofferruleModel->reduceMoney = $specialofferrule['reduceMoney'];
        }elseif (isset($specialofferrule['discountForAll']) && !empty($specialofferrule['discountForAll'])){
            $SpecialofferruleModel->discountForAll = $specialofferrule['discountForAll'];
        }
        $SpecialofferruleModel->specialOfferName = $specialofferrule['specialOfferName'];
    }

    private function checkparam($param){
        $Store = \app\admin\model\Store::get($param['storeId']);
        if(!$Store){
            return false;
        }
        if(!isset($param['ticket']['specialofferrule']['specialOfferName'])){
            return false;
        }
        if(empty($param['ticket']['backgroundImg'])){
            return false;
        }
        if(empty($param['ticket']['getGross'])){
            return false;
        }
        if(empty($param['ticket']['beginTime']) || empty($param['ticket']['endTime'])){
            return false;
        }
        return true;
    }

    /**
     * 券核销
     * @return \think\response\Json
     */
    public function WriteOffTicket(){
        (new WriteOffTicket())->goCheck();
        $param = Request::instance()->param();
        if(!$param['userId']){
            return show(config('status.ERROR_STATUS'),'用户id不能为空','用户id不能为空');
        }
        Db::startTrans();
        try{
            $Userreceivetic = Userreceivetic::get($param['id']);
            if($Userreceivetic){
                if($Userreceivetic->status == 0){
                    if($this->CheckTicket($Userreceivetic,$param)){
                        $Userreceivetic->status = 1;
                        $Userreceivetic->save();
                        $Storecancelrecord = new Storecancelrecord();
                        $Storecancelrecord->id = Helper::getUUID();
                        $Storecancelrecord->userId = $param['userId'];
                        $Storecancelrecord->storeId = $param['storeId'];
                        $Storecancelrecord->ticketId = $param['ticketId'];
                        $Storecancelrecord->status = 1;
                        $Storecancelrecord->cancelTime = date('Y-m-d H:i:s',time());
                        $Storecancelrecord->cancelOper = $param['userId'];
                        $Storecancelrecord->save();
                        Db::commit();
                        return show(config('status.SUCCESS_STATUS'),'核销成功','核销成功');
                    }else{
                        return show(config('status.ERROR_STATUS'),'不是此店铺的优惠券，不能核销','不是此店铺的优惠券，不能核销');
                    }
                }else{
                    return show(config('status.ERROR_STATUS'),'此优惠券可能已经核销过','此优惠券可能已经核销过');
                }
            }else{
                return show(config('status.ERROR_STATUS'),'此优惠券不存在','此优惠券不存在');
            }
        }catch (Exception $e){
            Db::rollback();
            return show(config('status.ERROR_STATUS'),'内部错误，核销失败','内部错误，核销失败');
        }


    }
    private function CheckTicket($Userreceivetic,$param){
        if($Userreceivetic->userId == $param['userId'] && $Userreceivetic->storeId == $param['storeId'] && $Userreceivetic->ticketId == $param['ticketId']){
            return true;
        }
        return false;
    }

    public function getTicketDetails(Request $request){
        $param = $request->param();
        if(!isset($param['ticketId']) || empty($param['ticketId'])){
            return show(config('status.ERROR_STATUS'),'缺少券Id','缺少券Id');
        }

        $Ticket = \app\admin\model\Ticket::where(['id'=>$param['ticketId'],'status'=>5])->find();
        if($Ticket){
            $Store = \app\admin\model\Store::get($Ticket->storeId);
            $Ticket['store'] = $Store;
            return show(config('status.SUCCESS_STATUS'),'ok',$Ticket);
        }else{
            return show(config('status.ERROR_STATUS'),'error','没找到数据');
        }

    }

    public function getAllTickets(Request $request){
        $param = $request->param();
        $start = $param['start'];
        $length = $this->pagelength;
        if(empty($param['city'])){
            return show(config('status.ERROR_STATUS'),'缺少城市信息','缺少城市信息');
        }
        $where = "WHERE a.status=5 AND (a.firstCommission>0 OR a.secCommission>0) AND s.city='$param[city]' AND endTime>now()";
        if(isset($param['lat']) && isset($param['lng'])){
            $field = "a.*, s.name as storeName, s.lat as lat, s.lng as lng,(round(6371393 * 2 * asin(sqrt(pow(sin(((lat * pi()) / 180 - ({$param['lat']} * pi()) / 180) / 2), 2) + cos(({$param['lat']} * pi()) / 180) * cos((lat * pi()) / 180) * pow(sin(((lng * pi()) / 180 - ({$param['lng']} * pi()) / 180) / 2), 2))))) AS distance";
            $Tickets = Db::query("SELECT {$field} FROM `ticket` AS a LEFT JOIN `store` AS s ON a.storeId=s.id {$where} ORDER BY distance ASC LIMIT {$start},{$length}");
            $count = count(Db::query("SELECT {$field} FROM `ticket` AS a LEFT JOIN `store` AS s ON a.storeId=s.id {$where}"));
        }else{
            $field = 'a.*, s.name as storeName';
            $Tickets = Db::query("SELECT {$field} FROM `ticket` AS a LEFT JOIN `store` AS s ON a.storeId=s.id {$where} ORDER BY a.create_time DESC LIMIT {$start},{$length}");
            $count = count(Db::query("SELECT {$field} FROM `ticket` AS a LEFT JOIN `store` AS s ON a.storeId=s.id {$where}"));
        }
        if(!empty($Tickets)){
            return show_page(config('status.SUCCESS_STATUS'),'ok',$count,$Tickets);
        }else{
            return show(2,'暂无数据',null);
        }
    }

    public function receivedTicket(Request $request){
        $param = $request->param();
        $ticketId = $param['ticketId'];
        $userId = $param['userId'];
        if(!$ticketId){
            return show(config('status.ERROR_STATUS'),'缺少优惠券ID','缺少优惠券ID');
        }
        $Userreceivetic = Userreceivetic::where(['ticketId'=>$ticketId,'userId'=>$userId,'status'=>0])->select();
        if($Userreceivetic){
            return show(config('status.SUCCESS_STATUS'),'ok',$Userreceivetic);
        }else{
            return show(config('status.ERROR_STATUS'),'error',[]);
        }
    }

    //核销记录
    public function getCancelRecord(Request $request){
        $param = $request->param();
        if(empty($param['storeId'])){
            return show(config('status.ERROR_STATUS'),'参数错误','参数错误');
        }
        $start = $param['start'];
        $length = $param['length'];
        $Storecancelrecord = Storecancelrecord::where(['storeId'=>$param['storeId'],'status'=>1])->order('cancelTime Desc')->limit($start,$length)->select();
        $count = count(Storecancelrecord::where(['storeId'=>$param['storeId'],'status'=>1])->select());
        if($Storecancelrecord){
            foreach ($Storecancelrecord as &$v){
                $Store = \app\admin\model\Store::get($v['storeId']);
                $v['store'] = $Store;
                $Ticket = \app\admin\model\Ticket::get($v['ticketId']);
                $v['ticket'] = $Ticket;
                $User = \app\common\model\User::get($v['userId']);
                $v['user'] = $User;
            }
            return show_page(config('status.SUCCESS_STATUS'),'ok',$count,$Storecancelrecord);
        }else{
            return show(2,'暂无核销记录',NULL);
        }
    }

    public function deleteStoreTickets(Request $request){
        $param = $request->param();
        if(empty($param['ticketId'])){
            return show(config('status.ERROR_STATUS'),'参数错误','参数错误');
        }
        $Ticket = \app\admin\model\Ticket::get($param['ticketId']);
        if($Ticket){
            $Userreceivetic = Userreceivetic::where(['ticketId'=>$Ticket->id,'status'=>0])->find();
            if($Userreceivetic){
                return show(2,'已有人领取该券,不能删除',null);
            }
            $Ticket->status = 3;
            $Ticket->save();
            return show(config('status.SUCCESS_STATUS'),'ok',1);
        }else{
            return show(2,'数据为空',null);
        }
    }

    //免费领券
    public function receiveTicket(Request $request){
        $param = $request->param();
        if(empty($param['ticketId']) || empty($param['storeId'])){
            return show(config('status.ERROR_STATUS'),'参数错误','参数错误');
        }
        try{
            $pay = new Pay();
            $check = $pay->checkticket($param);
            if(!$check['pass']){
                if($check['status'] == 1000){
                    return show(config('status.ERROR_STATUS'),'此优惠券已过期','此优惠券已过期');
                }elseif ($check['status'] == 2000){
                    return show(config('status.ERROR_STATUS'),'您已经领取过此优惠券，并且还没核销','您已经领取过此优惠券，并且还没核销');
                }else{
                    return show(config('status.ERROR_STATUS'),'此优惠券售罄','此优惠券售罄');
                }
            }
            $UserreceiveticModel = new Userreceivetic();
            $UserreceiveticModel->id = Helper::getUUID();
            $UserreceiveticModel->userId = $param['userId'];
            $UserreceiveticModel->storeId = $param['storeId'];
            $UserreceiveticModel->ticketId = $param['ticketId'];
            $UserreceiveticModel->receiveTicketTime = date('Y-m-d H:i:s',time());
            $UserreceiveticModel->save();
            $Ticket = \app\admin\model\Ticket::get($param['ticketId']);
            $Ticket->setDec('remainGross',1);
            Db::commit();
            return show(config('status.SUCCESS_STATUS'),'领取成功','领取成功');
        }catch (Exception $ex){
            Db::rollback();
            return show(config('status.ERROR_STATUS'),'领取失败','领取失败');
        }

    }

}